<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="600px" destroyOnClose showFooter>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './storeTag.data';
import {saveOrUpdate} from './storeTag.api';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
// 声明Emits
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//表单配置
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //重置表单
  await resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
  }
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增门店标签' : '编辑门店标签'));
//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    //提交表单
    values.userIds += ","
    await saveOrUpdate({...values}, isUpdate.value);
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
